﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TimScripts.BF4Rcon.Frostbite;
using NUnit.Framework;
using NUnit.Framework.Constraints;

namespace TimScripts.BF4Rcon.Test
{
    class MapRconClient : ISynchronousRconClient
    {
        private Queue<MapDataCreator> Responses = new Queue<MapDataCreator>();
        private MapDataCreator CurrentData;
        private int MapsSent;

        private Dictionary<string, Func<IList<string>, IList<string>>> ResponseFunctions = new Dictionary<string, Func<IList<string>, IList<string>>>(StringComparer.OrdinalIgnoreCase);

        private List<IMap> _AllMaps = new List<IMap>();
        public IList<IMap> AllMaps { get { return _AllMaps; } }

        public MapRconClient AddMap(MapName mapName, GameMode gameMode, int rounds)
        {
            Map map = new Map(mapName, gameMode, rounds);

            return AddMap(map);
        }

        public MapRconClient AddMap(Map map)
        {
            CurrentData.AddMaps(map);
            AllMaps.Add(map);

            return this;
        }

        public MapRconClient InsertMap(int index, MapName mapName, GameMode gameMode, int rounds)
        {
            Map map = new Map(mapName, gameMode, rounds);

            return InsertMap(index, map);
        }

        public MapRconClient InsertMap(int index, Map map)
        {
            CurrentData.InsertMaps(index, map);
            AllMaps.Insert(index, map);

            return this;
        }

        public MapRconClient RemoveMap(int index)
        {
            MapDataCreator targetData = null;
            int numSkipped = 0;
            int targetIndex = -1;

            if (index >= AllMaps.Count)
                throw new ArgumentOutOfRangeException("index");

            AllMaps.RemoveAt(index);

            foreach (MapDataCreator data in Responses)
            {
                if (index <= data.Count + numSkipped)
                {
                    targetData = data;
                    targetIndex = index - numSkipped;
                    break;
                }

                numSkipped += data.Count;
            }

            targetData.RemoveMap(targetIndex);

            return this;
        }

        public MapRconClient BeginNewResponse()
        {
            Responses.Enqueue(CurrentData = new MapDataCreator());

            return this;
        }

        public void Finish()
        {
            //final one with 0 maps
            Responses.Enqueue(new MapDataCreator());

            BeginNewResponse();
        }

        public void ResetMaps()
        {
            AllMaps.Clear();
            Responses.Clear();
            BeginNewResponse();
            MapsSent = 0;
        }

        public MapRconClient()
        {
            ResetMaps();

            AddResponder("maplist.list", List);
            AddResponder("maplist.add", Add); ;
            AddResponder("maplist.remove", Remove);
        }

        public IList<string> SendRequest(IEnumerable<string> words, int timeout)
        {
            throw new NotImplementedException();
        }

        public IList<string> SendRequest(IEnumerable<string> words)
        {
            string command;
            IList<string> data;
            Func<IList<string>, IList<string>> responder;

            if (!IsLoggedOn)
                return new List<string>(new[] { "LogInRequired" });

            command = words.ElementAt(0);

            Assert.True(ResponseFunctions.TryGetValue(command, out responder));

            data = responder(words.Skip(1).ToList());

            return data;
        }

        private IList<string> List(IList<string> requestData)
        {
            MapDataCreator mapData = Responses.Dequeue();
            int offset = int.Parse(requestData.ElementAtOrDefault(0) ?? "0");

            //ignore offset here, but check validity later
            IList<string> data = mapData.GetData("OK");

            Assert.AreEqual(MapsSent, offset);
            MapsSent += mapData.Count;

            return data;
        }

        private IList<string> Add(IList<string> requestData)
        {
            string rawMapName = requestData[0];
            string rawGameMode = requestData[1];
            int rounds = int.Parse(requestData[2]);
            Map map = Map.Parse(rawMapName, rawGameMode, rounds);
            int index;

            if (rounds < 1)
                return Response("InvalidRoundsPerMap");

            if (map.MapName == MapName.Unknown)
                return Response("InvalidMap");

            if (requestData.Count >= 4)
            {
                index = int.Parse(requestData[3]);

                if (index < 0 || index > AllMaps.Count)
                    return Response("InvalidMapIndex");

                InsertMap(index, map);
            }
            else
            {
                AddMap(map);
            }

            return Response("OK");
        }

        private IList<string> Remove(IList<string> requestData)
        {
            int index = int.Parse(requestData[0]);

            if (index < 0 || index > AllMaps.Count)
                return Response("InvalidMapIndex");

            RemoveMap(index);

            return Response("OK");
        }

        private IList<string> Response(params string[] words)
        {
            return new List<string>(words);
        }

        public bool IsLoggedOn
        {
            get;
            set;
        }

        public bool LogOn(string password)
        {
            throw new NotImplementedException();
        }

        private void AddResponder(string command, Func<IList<string>, IList<string>> responderFunc)
        {
            ResponseFunctions[command] = responderFunc;
        }
    }
}
